package train_handler

import (
	"fmt"
	"net/http"
	"peilian-api/app/global/bind"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	"peilian-api/app/services/train_service"
	"peilian-api/utils/format"
	"peilian-api/utils/paginate"
	"strconv"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

// 面试记录导出
func ExportTrainLog(ctx *gin.Context) {
	var ts model.ExportTrainLog
	if err := bind.ShouldBinding(ctx, &ts); err != nil {
		format.NewResponseJson(ctx).Err(30001, err.Error())
		return
	}
	_, _, url, err := train_service.ExportTrainLog(ctx, ts)
	if err != nil {
		format.NewResponseJson(ctx).Err(30002, err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessObj(struct {
		Url string `json:"url"`
	}{Url: url})
}

// 查询用户面试记录
func GetTrainList(ctx *gin.Context) {
	var gr model.GetStudentRequest
	if err := bind.ShouldBinding(ctx, &gr); err != nil {
		format.NewResponseJson(ctx).Err(30001, err.Error())
		return
	}
	count, out, err := train_service.GetTrailList(ctx, gr)
	if err != nil {
		format.NewResponseJson(ctx).Err(30002, err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessDataList(int(count), out)
}

// 记录数据查询
func QueryTrainLog(ctx *gin.Context) {
	var ts model.QueryTrainLogReq
	if err := bind.ShouldBinding(ctx, &ts); err != nil {
		format.NewResponseJson(ctx).Err(30001, err.Error())
		return
	}
	opt := ts.Opt
	out, count, url, err := train_service.QueryTrainLog(ctx, ts, opt)
	if err != nil {
		format.NewResponseJson(ctx).Err(30002, err.Error())
		return
	}
	if opt == 0 {
		format.NewResponseJson(ctx).SuccessDataList(int(count), out)
		return
	} else if opt == 1 {
		format.NewResponseJson(ctx).SuccessObj(struct {
			Url string `json:"url"`
		}{Url: url})
		return
	}
}

func QueryFilter(query *model.QueryTrainLogReqThird) func(db *gorm.DB) *gorm.DB {
	return func(db *gorm.DB) *gorm.DB {
		if query.Query != "" {
			likeStr := fmt.Sprintf("%%%s%%", query.Query)
			db = db.Where(
				variable.DB.MySQL.Where("session.user_name like ?", likeStr).
					Or("session.user_phone like ?", likeStr).
					Or("session.sno like ?", likeStr),
			)
		}
		if query.Career != "" {
			db = db.Where("session.career_name=?", query.Career)
		}
		if query.StartTime != "" {
			db = db.Where("session.created_at>=?", query.StartTime)
		}
		if query.EndTime != "" {
			db = db.Where("session.created_at<=?", query.EndTime)
		}
		if query.StartScore != 0 {
			db = db.Where("session.total_score>=? ", query.StartScore)
		}
		if query.EndScore != 0 {
			db = db.Where("session.total_score<=?", query.EndScore)
		}
		if !query.IsAll {
			db = db.Where("session.duration <> 0")
		}
		return db
	}
}

func ThirdTrainLog(c *gin.Context) {
	var query model.QueryTrainLogReqThird
	if err := bind.ShouldBinding(c, &query); err != nil {
		format.NewResponseJson(c).Err(30001, err.Error())
		return
	}
	agentName, _ := c.Get("agentName")
	agentType, _ := c.Get("agentType")
	records := make([]*model.QueryTrainLogResp, 0)
	selectFields := []string{
		"session.id", "session.user_name as name", "session.user_phone as phone", "session.school",
		"session.academy", "session.profession", "session.education", "session.grade",
		"session.career_name as career", "session.url as report_url", "session.status",
		"cast(session.total_score as unsigned) as score", "session.duration", "session.sno",
		"session.finish_at as finish_time_obj", "session.train_at as train_time_obj",
		"session.type", "career.report_type", "session.career_id",
	}
	baseDb := variable.DB.MySQL.Model(&tables.Session{}).Select(selectFields).
		Joins("left join career on session.career_id=career.id").Order("-session.created_at").
		Where(fmt.Sprintf("%s=?", agentType), agentName).Scopes(QueryFilter(&query))
	var count int64
	if err := baseDb.Count(&count).Error; err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	pageDb := baseDb.Scopes(paginate.Paginate(c.Request))
	rows, err := pageDb.Rows()
	if err != nil {
		format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
		return
	}
	defer rows.Close()
	for rows.Next() {
		var record model.QueryTrainLogResp
		if err := variable.DB.MySQL.ScanRows(rows, &record); err != nil {
			format.NewResponseJson(c).Err(http.StatusBadRequest, err.Error())
			return
		}
		if record.FinishTimeObj.UnixMicro() > 0 {
			record.FinishTime = record.FinishTimeObj.Format("2006-01-02 15:04:05")
		}
		if record.TrainTimeObj.UnixMicro() > 0 {
			record.TrainTime = record.TrainTimeObj.Format("2006-01-02 15:04:05")
		}
		duration, _ := strconv.Atoi(record.Duration)
		record.Duration = fmt.Sprintf("%d分%d秒", duration/60, duration%60)
		var photoUri = variable.Config.UfsInfo.UfsUrl + variable.Config.UfsInfo.BucketPrefix
		record.ReportUrl = photoUri + record.ReportUrl
		if record.ReportType == "web" {
			record.ReportUrl = fmt.Sprintf(
				"https://growup.aminer.cn/%s/web-report#?reportId=%d&careerId=%d",
				variable.Env, record.Id, record.CareerId,
			)
		}
		record.Type = tables.UseTypeMap[record.Type]
		records = append(records, &record)
	}

	format.NewResponseJson(c).SuccessDataList(int(count), records)
}

// 记录详情
func QueryTrainLogDetail(ctx *gin.Context) {
	var qt model.QueryTrainLogDetailReq
	if err := bind.ShouldBinding(ctx, &qt); err != nil {
		format.NewResponseJson(ctx).Err(30001, err.Error())
		return
	}
	out, err := train_service.QueryTrainLogDetail(ctx, qt)
	if err != nil {
		format.NewResponseJson(ctx).ErrObj(30002, err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessObj(out)
}

// 删除数据记录
func DeleteTrainLog(ctx *gin.Context) {
	var dtl model.TrainLogIdsReq
	if err := bind.ShouldBinding(ctx, &dtl); err != nil {
		format.NewResponseJson(ctx).Err(30002, err.Error())
		return
	}
	if err := train_service.DeleteTrainLog(ctx, dtl.Ids); err != nil {
		format.NewResponseJson(ctx).Err(30002, err.Error())
		return
	}
	format.NewResponseJson(ctx).SuccessObj(struct{}{})
}
